package edu.spec.basic.service.impl;

import edu.spec.basic.dao.iface.IUserDao;
import edu.spec.basic.model.User;
import edu.spec.basic.model.dto.UserDto;
import edu.spec.basic.model.enumeration.AccountStatus;
import edu.spec.basic.model.enumeration.YesNo;
import edu.spec.basic.service.iface.IUserService;
import edu.spec.basic.util.FileTool;
import edu.spec.basic.util.XlsTools;
import org.madgecko.basic.model.Pager;
import org.madgecko.basic.util.SecurityUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Service("userService")
public class UserService implements IUserService {

	@Inject
	private IUserDao userDao;

	@Override
	public void add(User user) {
		userDao.add(user);
	}

	@Override
	public void delete(Integer id) {
		//TODO 删除用户关联的内容
		userDao.delete(id);
	}

	@Override
	public void update(User user) {
		userDao.update(user);
	}

	@Override
	public boolean importIn(MultipartFile file, HttpServletRequest req, HttpSession session) {
		String fullStorePath = FileTool.saveTempFile(file, req);
		File importFile = new File(fullStorePath);
		Collection col = XlsTools.importExcel(importFile, User.class, "");
		try {
			for(Object o : col){
				User u = (User)o;
				String username = u.getUsername();
				User ifUser = userDao.loadByName(username);
				if(ifUser!=null){
					continue;
				}
				u.setPassword(SecurityUtil.md5("aaa"));
				u.setAccountStatus(AccountStatus.NORMAL);
				u.setCreateDate(new Date());
				User cu = (User)session.getAttribute("user");
				u.setOwner(userDao.load(cu.getId()));
				this.add(u);
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		importFile.deleteOnExit();
		return true;
	}

	@Override
	public User load(Integer id) {
		return userDao.load(id);
	}

	@Override
	public Pager<User> findUserByCon(Integer status, String con) {
		return userDao.findUserByCon(status, con);
	}

    @Override
	public User loadByName(String name){
		return userDao.loadByName(name);
	}

    @Override
    public User loadByOpenId(String openId) {
        return userDao.loadByOpenId(openId);
    }


    @Override
    public List<Integer> listIdsByFormal(YesNo yesNo) {
        return userDao.listIdsByFormal(yesNo);
    }

    @Override
    public List<Integer> listIdsByCommunist(YesNo yesNo) {
        return userDao.listIdsByCommunist(yesNo);
    }

    @Override
    public List<User> listAll() {
        return userDao.listAll();
    }

    @Override
    public List<UserDto> listUserDtoByIdString(String idString) {
        return userDao.listUserDtoByIdString(idString);
    }

}
